<template>
    <div class="grid card">
        <div class="data-card card" v-for="(item, index) in datas" :key="index" :style="{backgroundColor: colors[index]}">
            <div class="title">
                {{ item.title }}
            </div>
            <div class="flex flex-between">
                <el-icon :size="40">
                    <component :is="item.icon"></component>
                </el-icon>
                <span class="count">
                    <CountTo :startVal="0" :endVal="Number(item.count)" :duration="3000"></CountTo>
                </span>
            </div>
        </div>
    </div>
    
    <!-- 添加折线图组件 -->
    <div class="flex flex-between mt-20">
        <div class="card mr-20" style="width:70%">
            <EchartsLine :x-data="lineData.x" :y-data="lineData.y" />
        </div>
        <div class="card" style="width:25%">
            <EchartsPie :data="pieData"></EchartsPie>
        </div>
    </div>
</template>

<script setup>
import { CountTo } from "vue3-count-to";
import { getDatas, getWeekDatas, getContentDatas } from "@/api/dashboard.js"
import { reactive, onMounted, ref } from "vue";
import EchartsLine from '@/components/EchartsLine.vue'
import EchartsPie from '@/components/EchartsPie.vue'

const colors = ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C"]
const datas = reactive([]);

const lineData = reactive({
  x: [],
  y: []
});
const pieData = ref([])

onMounted(() => {
  getDatas().then(res => {
    // 确保 count 是数字类型
    datas.splice(0, datas.length, ...res.data.map(item => ({
      ...item,
      count: Number(item.count)
    })));
  }).catch(error => {
    console.error('获取统计数据失败:', error);
  });

  getWeekDatas().then(res => {
    if (res.code == 1) {
      lineData.x = res.data.keys || [];
      lineData.y = res.data.values || [];
    }
  }).catch(error => {
    console.error('获取图表数据失败:', error);
    // 设置默认数据以防接口失败
    lineData.x = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    lineData.y = [820, 932, 901, 934, 1290, 1330, 1320];
  });

  getContentDatas().then(res => {
    if (res.code == 1) {
      pieData.value = res.data.values;
    }
  })
});
</script>

<style scoped lang="scss">
.grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 15px;
}

.data-card {
    color: #fff;
}

.count {
    font-size: 32px;
    font-weight: bold;
}

.chart-container {
    margin-top: 20px;
}
</style>